package tv.acgn.advertisement.publish.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tv.acgn.advertisement.servicebase.vo.CommonResponse;

/**
 * @program: advertisement-ad-publist-interceptor
 * @description: 远程请求 全局异常处理器
 * @author: junG
 * @create: 2019-05-01 18:16
 **/

@RestControllerAdvice
@Slf4j
public class GlobalRequestExceptionHandler {

    /**
     *
     * @author junG
     * @description 参数校验异常 捕获处理
     * @date 18:26 2019/5/1
     * @param [request, response, ex]
     * @return {@link tv.acgn.advertisement.servicebase.vo.CommonResponse<java.lang.String>}
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    @ResponseStatus(code= HttpStatus.BAD_REQUEST)
    public CommonResponse<String> handlerAdSysBusinessExcpetion(HttpServletRequest request,
                                                                HttpServletResponse response,
                                                                ConstraintViolationException ex) {
        StringBuilder sb=new StringBuilder();
        for (ConstraintViolation<?> exConstraintViolation : ex.getConstraintViolations()) {
                sb.append(exConstraintViolation.getMessage());
        }

        log.error("请求参数错误 未通过校验 {}",sb.toString());
        CommonResponse<String> commonResponse = new CommonResponse<>(-400, "程序运行出现业务异常");
        commonResponse.setSuccess(false);
        commonResponse.setMessage(sb.toString());
        //TODO 请求参数异常处理
        return commonResponse;
    }
}
